package com.sxjh.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxjh.entity.Unlock;
import com.sxjh.entity.param.UnlockListParam;
import com.sxjh.entity.result.UnlockListResult;
import com.sxjh.mapper.UnlockMapper;
import com.sxjh.service.UnlockService;
import com.sxjh.socket.AppUnlockSocketServer;
import com.sxjh.socket.UnlockSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class UnlockServiceImpl extends ServiceImpl<UnlockMapper, Unlock> implements UnlockService {

    @Autowired
    private UnlockMapper unlockMapper;

    @Override
    public IPage<UnlockListResult> list(IPage iPage, UnlockListParam param) {
        return unlockMapper.list(iPage, param);
    }

    @Override
    public void receipt(List<Integer> ids) {
        unlockMapper.receipt(ids);
    }

    @Async(value = "taskExecutor")
    @Override
    public void pushNotice(Integer id) {
        IPage<Unlock> iPage = new Page(1, 30);
        LambdaQueryWrapper<Unlock> queryWrapper = new LambdaQueryWrapper<>();
        //只查询未读的消息
        if (id != null) {
            queryWrapper.eq(Unlock::getReaded, 2);
            queryWrapper.orderByDesc(Unlock::getCreatedAt, Unlock::getIsPush);
            iPage = page(iPage, queryWrapper);
            if (iPage != null && CollUtil.isNotEmpty(iPage.getRecords())) {
                String message = JSON.toJSONString(iPage.getRecords());
                try {
                    UnlockSocketServer.sendInfo(message, null);
                    AppUnlockSocketServer.sendInfo(message, null);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
